<template>
    <div class="result-container">
        <h2>表单填写结果</h2>
        <div class="result-meta">
            <span>提交时间: {{ createTime }}</span>
            <span class="status-badge" :class="`status-${status}`">
                {{ getStatusText(status) }}
            </span>
        </div>
        <div v-for="field in processedFields" :key="field.id" class="result-group">
            <div class="field-header">
                <strong>{{ field.name }}</strong>
                <span class="field-type">{{ field.type }}字段</span>
            </div>

            <!-- 文件字段 -->
            <div v-if="field.type === 'file'" class="file-display">
                <div v-if="loadingImages[field.value]" class="loading-spinner">
                    <i class="el-icon-loading"></i>
                    <span>加载中...</span>
                </div>
                <el-image v-else :src="imageUrls[field.value]" :preview-src-list="getPreviewList(field.value)"
                    fit="contain" class="result-image" @error="handleImageError(field.value)">
                    <div slot="error" class="image-error">
                        <i class="el-icon-picture-outline"></i>
                        <span>图片加载中...</span>
                    </div>
                </el-image>
            </div>

            <!-- 复选框字段 -->
            <div v-else-if="field.type === 'checkbox'" class="checkbox-field">
                <el-tag v-for="(item, idx) in field.value" :key="idx" type="info" class="checkbox-tag">
                    {{ item }}
                </el-tag>
            </div>

            <!-- 其他字段 -->
            <div v-else class="field-value">
                {{ field.value || '空' }}
            </div>
        </div>
        <div v-if="showActions" class="action-buttons">
            <el-button type="success" @click="$emit('status-change', 1)" :loading="statusLoading">
                通过
            </el-button>
            <el-button type="danger" @click="$emit('status-change', 2)" :loading="statusLoading">
                拒绝
            </el-button>
        </div>

    </div>
</template>

<script>
import { getFileUrl } from '@/api/cd/form'

export default {
    props: {
        formFields: Array,
        formData: String,
        status: {
            type: Number,
            default: 0
        },
        createTime: String
    },
    data() {
        return {
            imageUrls: {},
            loadingImages: {},
            statusLoading: false
        }
    },
    computed: {
        processedFields() {
            try {
                return JSON.parse(this.formData) || [];
            } catch {
                return [];
            }
        },

        //     createTime() {
        //     try {
        //         const parsedData = JSON.parse(this.formData) || {};
        //         // 使用浏览器内置方法格式化时间
        //         return parsedData.createTime ? new Date(parsedData.createTime).toLocaleString() : '未知时间';
        //     } catch {
        //         return '未知时间';
        //     }
        // },

        showActions() {
            return this.status === 0; // 只有待审批状态显示操作按钮
        }
    },
    methods: {
        async loadAllImages() {
            const fileFields = this.processedFields.filter(f => f.type === 'file');

            await Promise.all(fileFields.map(async field => {
                this.$set(this.loadingImages, field.value, true);
                try {
                    // 假设 API 返回 { url: "/path/to/image.jpg" }
                    const response = await getFileUrl(field.value);
                    let imageUrl = response.url || response.data?.url; // 兼容不同响应结构

                    // 处理中文文件名（URL编码）
                    imageUrl = encodeURI(imageUrl);
                    imageUrl = '/lqq' + imageUrl;

                    // 确保是完整 URL（如果后端返回的是相对路径）
                    if (imageUrl && !imageUrl.startsWith('http')) {
                        imageUrl = `${window.location.origin}${imageUrl}`;
                    }

                    this.$set(this.imageUrls, field.value, imageUrl);
                    //console.log('最终图片URL:', imageUrl); // 调试用
                } catch (e) {
                    console.error('加载失败:', field.value, e);
                    this.$set(this.imageUrls, field.value, ''); // 失败时清空
                } finally {
                    this.$set(this.loadingImages, field.value, false);
                }
            }));
        },

        getStatusText(status) {
            const statusMap = {
                0: '待审批',
                1: '已通过',
                2: '已拒绝',
                3: '无需审批'
            };
            return statusMap[status] || '未知状态';
        },

        handleImageError(fileId) {
            this.$set(this.imageUrls, fileId, '');
        },

        getPreviewList(currentFile) {
            const fileFields = this.processedFields
                .filter(f => f.type === 'file')
                .map(f => this.imageUrls[f.value])
                .filter(url => url);

            const currentIndex = fileFields.indexOf(this.imageUrls[currentFile]);
            if (currentIndex > 0) {
                // 将当前图片放到首位实现轮播效果
                return [
                    fileFields[currentIndex],
                    ...fileFields.slice(0, currentIndex),
                    ...fileFields.slice(currentIndex + 1)
                ];
            }
            return fileFields;
        }
    },
    mounted() {
        this.loadAllImages();
    }
}
</script>

<style scoped>
.result-container {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.result-meta {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    color: #666;
    font-size: 14px;
}

.status-badge {
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 12px;
}

.status-0 {
    background: #fdf6ec;
    color: #e6a23c;
}

.status-1 {
    background: #f0f9eb;
    color: #67c23a;
}

.status-2 {
    background: #fef0f0;
    color: #f56c6c;
}

.status-3 {
    background: #f4f4f5;
    color: #909399;
}

.result-group {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px dashed #eee;
}

.field-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
}

.field-type {
    color: #999;
    font-size: 12px;
}

.file-display {
    margin-top: 10px;
}

.result-image {
    max-width: 100%;
    max-height: 300px;
    border: 1px solid #eee;
    border-radius: 4px;
}

.checkbox-field {
    margin-top: 8px;
}

.checkbox-tag {
    margin-right: 8px;
    margin-bottom: 5px;
}

.action-buttons {
    margin-top: 20px;
    text-align: center;
}

.loading-spinner,
.image-error {
    display: flex;
    align-items: center;
    color: #999;
    font-size: 14px;
}

.loading-spinner i,
.image-error i {
    margin-right: 5px;
}
</style>
